package com.game.utils.security;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class SHA1 {
	private static final String ENCODE = "UTF-8";

	private static MessageDigest sha1MD;

	public static String code(String text) {
		if (null == sha1MD) {
			try {
				sha1MD = MessageDigest.getInstance("SHA-1");
			} catch (NoSuchAlgorithmException e) {
				System.err.println("@SHA1 No such SHA-1 algorithm.");
				return null;
			}
		}
		try {
			sha1MD.update(text.getBytes(ENCODE), 0, text.length());
		} catch (UnsupportedEncodingException e) {
			sha1MD.update(text.getBytes(), 0, text.length());
		}
		return toHexString(sha1MD.digest());
	}

	private static String toHexString(byte[] hashs) {
		StringBuffer sBuffer = new StringBuffer();
		for (byte hash : hashs) {
			sBuffer.append(Integer.toString((hash & 0xFF) + 0x100, 16)
					.substring(1));
		}
		return sBuffer.toString();
	}
}
